package com.bidevalution.business.job;

import com.bidevalution.business.factory.StepJobJdbcFactory;
import com.bidevalution.business.service.JdbcTemplateService;
import com.bidevalution.dao.entity.*;
import com.bidevalution.support.context.Constants;
import com.google.common.collect.Maps;
import com.qtp.core.util.DateUtil;
import com.qtp.core.util.IdsUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @description:汇总投标单位技术、资信和商务总分 约定:be_evalution_outcome的c19存单个专家对这个单位的分数汇总，c20存所有专家对这个单位的分数汇总
 * @author: xiayf
 * @date: 2019-11-21 14:08
 */
public class StepCountScoreResultJob implements StepJobJdbcFactory {

    private JdbcTemplateService jdbcTemplateService;

    private Logger log = LogManager.getLogger(getClass());

    @Override
    public Boolean execute(BeSectionStepJob beSectionStepJob, String submitCode, String expertId, String layoutCode) throws Exception {
        try {
            Map<String, Object> paramMap = Maps.newHashMap();
            paramMap.put("sectionId", beSectionStepJob.getSectionId());
            paramMap.put("sectionStepId", beSectionStepJob.getSectionStepId());
            paramMap.put("submitCode", submitCode);
            paramMap.put("isDel", "0");
            StringBuilder sb = new StringBuilder();
            //Y 表示此环节只能组长打分，因此只查询组长的数据保存（目前主要用于资信标）
            if(Constants.TRUE.equals(beSectionStepJob.getJobContent())){
                sb.append(" SELECT a.enterprise_id enterprise_id,a.expert_id expert_id,a.c19 c19,a.c20 c20 ");
                sb.append(" FROM be_section_expert_info b ");
                sb.append(" LEFT JOIN be_evalution_outcome a ON a.section_id=b.section_id AND a.section_step_id=:sectionStepId and a.is_del='0' AND b.seq_id=a.expert_id ");
                sb.append(" where b.section_id=:sectionId AND b.is_manager=1 ");
            }else{
                sb.append(" SELECT distinct enterprise_id,expert_id,c19,c20 FROM be_evalution_outcome ");
                sb.append(" WHERE section_id=:sectionId AND section_step_id=:sectionStepId AND submit_code=:submitCode AND is_del=:isDel ");
                sb.append(" ORDER BY create_time DESC ");
            }
            //获取此环节投标单位评审结果
            List<BeEvalutionOutcome> dataList = jdbcTemplateService.selectForList(sb.toString(), paramMap, BeanPropertyRowMapper.newInstance(BeEvalutionOutcome.class));
            //获取标段环节数据
            BeSectionStep beSectionStep = jdbcTemplateService.selectForObject("SELECT step_type,step_code FROM be_section_step WHERE seq_id=:sectionStepId",
                    paramMap, BeanPropertyRowMapper.newInstance(BeSectionStep.class));
            //更新投标单位的汇总分数
            if (dataList != null && !dataList.isEmpty()) {
                paramMap.put("stepType", beSectionStep.getStepType());
                paramMap.put("sectionStepCode", beSectionStep.getStepCode());
                List<BeEvalutionScoreDetail> ScoreList = new ArrayList<>();
                List<String> enterIdList = new ArrayList<>();
                BeEvalutionScoreDetail beEvalutionScoreDetail;
                for (BeEvalutionOutcome beEvalutionOutcome : dataList) {
                    if (StringUtils.isNotBlank(beEvalutionOutcome.getC19())) {
                        beEvalutionScoreDetail = new BeEvalutionScoreDetail();
                        beEvalutionScoreDetail.setSeqId(IdsUtil.uuid());
                        beEvalutionScoreDetail.setEnterpriseId(beEvalutionOutcome.getEnterpriseId());
                        beEvalutionScoreDetail.setExpertId(beEvalutionOutcome.getExpertId());
                        beEvalutionScoreDetail.setScore(beEvalutionOutcome.getC19());
                        beEvalutionScoreDetail.setSectionId(beSectionStepJob.getSectionId());
                        beEvalutionScoreDetail.setStepType(beSectionStep.getStepType());
                        beEvalutionScoreDetail.setSectionStepCode(beSectionStep.getStepCode());
                        beEvalutionScoreDetail.setCreateTime(DateUtil.now());
                        beEvalutionScoreDetail.setUpdateTime(DateUtil.now());
                        ScoreList.add(beEvalutionScoreDetail);
                    }
                    //该企业没有更新过
                    if (!enterIdList.contains(beEvalutionOutcome.getEnterpriseId())) {
                        enterIdList.add(beEvalutionOutcome.getEnterpriseId());
                        Map<String, Object> pMap = Maps.newHashMap();
                        pMap.put("sectionId", beSectionStepJob.getSectionId());
                        pMap.put("enterpriseId", beEvalutionOutcome.getEnterpriseId());
                        if ("1".equals(beSectionStep.getStepType())) {
                            pMap.put("technologyScore", beEvalutionOutcome.getC20());
                            jdbcTemplateService.update("UPDATE be_section_enterprise SET technology_score=:technologyScore WHERE section_id=:sectionId AND seq_id=:enterpriseId"
                                    , pMap);
                        } else if ("2".equals(beSectionStep.getStepType())) {
                            pMap.put("businessScore", beEvalutionOutcome.getC20());
                            jdbcTemplateService.update("UPDATE be_section_enterprise SET business_score=:businessScore WHERE section_id=:sectionId AND seq_id=:enterpriseId"
                                    , pMap);
                        } else if ("3".equals(beSectionStep.getStepType())) {
                            pMap.put("compositeScore", beEvalutionOutcome.getC20());
                            jdbcTemplateService.update("UPDATE be_section_enterprise SET composite_score=:compositeScore WHERE section_id=:sectionId AND seq_id=:enterpriseId"
                                    , pMap);
                        }
                    }
                }
                //删除存在记录
                jdbcTemplateService.update("DELETE FROM be_evalution_score_detail WHERE section_id=:sectionId AND step_type=:stepType AND section_step_code=:sectionStepCode", paramMap);
                //批量转数组
                SqlParameterSource[] scoreSources = SqlParameterSourceUtils.createBatch(ScoreList);
                jdbcTemplateService.bathInsert(" INSERT INTO be_evalution_score_detail(seq_id,enterprise_id,section_id,expert_id,score,step_type,section_step_code,create_time,update_time) " +
                        " VALUES(:seqId,:enterpriseId,:sectionId,:expertId,:score,:stepType,:sectionStepCode,:createTime,:updateTime) ", scoreSources);
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public void setJdbcTemplateService(JdbcTemplateService jdbcTemplateService) {
        this.jdbcTemplateService = jdbcTemplateService;
    }
}
